const fs = require('fs')
const path = require('path')

// 获取某日期在当月的第几周
function getWeekOfMonth(dateString) {
  const date = new Date(dateString)
  const startOfMonth = new Date(date.getFullYear(), date.getMonth(), 1)
  const dayOfWeek = startOfMonth.getDay()
  const adjustedDate = date.getDate() + dayOfWeek
  return Math.ceil(adjustedDate / 7)
}

// 获取当前周的起止日期
function getCurrentWeekRange() {
  const now = new Date()
  const dayOfWeek = now.getDay()
  const startOfWeek = new Date(now)
  startOfWeek.setDate(now.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1)) // 周一
  const endOfWeek = new Date(startOfWeek)
  endOfWeek.setDate(startOfWeek.getDate() + 6) // 周日
  return { startOfWeek, endOfWeek }
}

// 去除 YAML 前后文块
function removeYamlFrontMatter(content) {
  return content.replace(/---\s*[\s\S]*?\s*---\s*/, '')
}

// 构建周报文件路径
function buildWeeklyReportPath(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const week = getWeekOfMonth(date.toISOString().split('T')[0])
  return path.join(__dirname, `周报/${year}年${month}月第${week}周周报.md`)
}

// 获取起止日期
function getWeekRange(startDate, endDate) {
  if (startDate && endDate) {
    return {
      startOfWeek: new Date(startDate),
      endOfWeek: new Date(endDate),
    }
  } else {
    return getCurrentWeekRange()
  }
}

// 生成日期范围内的所有日期字符串
function getDatesInRange(startDate, endDate) {
  const dates = []
  let currentDate = new Date(startDate)
  while (currentDate <= endDate) {
    dates.push(currentDate.toISOString().split('T')[0])
    currentDate.setDate(currentDate.getDate() + 1)
  }
  return dates
}

// 主函数
function generateWeeklyReport(startDate, endDate) {
  const { startOfWeek, endOfWeek } = getWeekRange(startDate, endDate)
  const OUTPUT_FILE = buildWeeklyReportPath(startOfWeek)

  console.log('Start of Week:', startOfWeek.toISOString().split('T')[0])
  console.log('End of Week:', endOfWeek.toISOString().split('T')[0])
  console.log('Output File:', OUTPUT_FILE)

  const datesInRange = getDatesInRange(startOfWeek, endOfWeek)
  const DAILY_REPORTS_DIR = path.join(__dirname, '日报')

  let weeklyReportContent = ''

  datesInRange.forEach(dateStr => {
    const dailyReportPath = path.join(DAILY_REPORTS_DIR, `${dateStr}.md`)
    if (fs.existsSync(dailyReportPath)) {
      const dailyContent = fs.readFileSync(dailyReportPath, 'utf-8')
      const newDailyContent = removeYamlFrontMatter(dailyContent)
      weeklyReportContent += `# ${dateStr}\n\n${newDailyContent}\n\n`
    } else {
      console.warn(`Daily report not found for date: ${dateStr}`)
    }
  })

  fs.writeFileSync(OUTPUT_FILE, weeklyReportContent)
  console.log(`Weekly report generated: ${OUTPUT_FILE}`)
}

// 示例调用：传入起止时间
// generateWeeklyReport('2024-11-18', '2024-11-24')

// 示例调用：使用当前周的起止时间
generateWeeklyReport()
